define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'ykjp/sell/delivery/index' + location.search,
                    add_url: 'ykjp/sell/delivery/add',
                    edit_url: 'ykjp/sell/delivery/edit',
                    detail_url: "ykjp/sell/delivery/detail",
                    del_url: 'ykjp/sell/delivery/del',
                    multi_url: 'ykjp/sell/delivery/multi',
                    delivery_url: 'ykjp/sell/delivery/delivery',
                    table: 'ykjp_delivery',
                }
            });

            var table = $("#table");
            //给添加按钮添加`data-area`属性
            $(".btn-add").data("area", ["100%", "100%"]);
            //当内容渲染完成给编辑按钮添加`data-area`属性
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                $(".btn-editone").data("area", ["100%", "100%"]);
            });
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {
                            checkbox: true, formatter: function (value, row, index) {
                                if (row.status == 0) {
                                    return {
                                        disabled: false,
                                    };
                                } else {
                                    return {
                                        disabled: true,
                                    }

                                }
                            }
                        },
                        {field: 'code', title: __('Code')},
                        {field: 'billing_time', title: __('Billing_time'), operate: 'RANGE', addclass: 'datetimerange', formatter: Table.api.formatter.datetime, datetimeFormat: "YYYY-MM-DD"},
                        {field: 'customer_name', title: __('Customer_name')},
                        {field: 'totalNums', title: __('Quantity'), operate: 'BETWEEN'},
                        {field: 'status_list', title: __('Status_list'), searchList: {"-1": __('Status_list -1'), "1": __('Status_list 1'), "2": __('Status_list 2'), "3": __('Status_list 3'), "4": __('Status_list 4'), "5": __('Status_list 5'), "6": __('Status_list 6')}, formatter: Table.api.formatter.normal},
                        {field: 'updatetime', title: __('Updatetime'), operate: 'RANGE', addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
                        // {field: 'code', title: __('Code')},
                        // {field: 'delivery_time', title: __('Delivery_time'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime,datetimeFormat:"YYYY-MM-DD"},
                        // {field: 'contact', title: __('Contact')},
                        // {field: 'phone', title: __('Phone')},
                        // {field: 'the_way', title: __('The_way'), searchList: {"2":__('The_way 2'),"1":__('The_way 1'),"0":__('The_way 0')}, formatter: Table.api.formatter.normal},
                        // {field: 'status', title: __('Status'), searchList: {"2":__('Status 2'),"1":__('Status 1'),"0":__('Status 0'),"3":__('Status 3')}, formatter: Table.api.formatter.status},
                        // {field: 'remark', title: __('Remark')},
                        // {field: 'billing_time', title: __('Billing_time'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime,datetimeFormat:"YYYY-MM-DD"},
                        // {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime,datetimeFormat:"YYYY-MM-DD"},
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table, events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'addtabs',
                                    title: __('look'),
                                    classname: 'btn btn-xs btn-primary  btn-addtabs',
                                    icon: 'fa fa-pencil-square-o',
                                    url: $.fn.bootstrapTable.defaults.extend.detail_url,
                                }, {
                                    name: 'yes',
                                    title: __('Status_list 6'),
                                    classname: 'btn btn-xs btn-success btn-magic btn-ajax',
                                    icon: 'fa fa-rocket',
                                    url: $.fn.bootstrapTable.defaults.extend.delivery_url,
                                    hidden: function (row) {
                                        if (row.status_list == 5) {
                                            return false;
                                        } else {
                                            return true;
                                        }
                                    },
                                    success: function (data, ret) {
                                        //如果需要阻止成功提示，则必须使用return false;
                                        //return false;
                                        layer.msg('确认出库成功', {
                                            time: 2000, //2s后自动关闭
                                            end: function () {
                                                location.reload();
                                            }
                                        })
                                    },
                                    error: function (data, ret) {
                                        Layer.alert(ret.msg);
                                        return false;
                                    }
                                }
                            ],
                            formatter: Table.api.formatter.operate,
                            formatter: function (value, row, index) {
                                var that = $.extend({}, this);
                                var table = $(that.table).clone(true);
                                if (row.status == 3) {
                                    $(table).data("operate-del", null);
                                }
                                that.table = table;
                                return Table.api.formatter.operate.call(that, value, row, index);
                            }
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'ykjp/purchase/storage/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '130px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'ykjp/purchase/storage/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'ykjp/purchase/storage/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            //显示客户列表
            $("#c-supplier").focus(function () {
                $("#myModal").modal("show");
            });

            $('#myModal').on('show.bs.modal', function (e) {
                Controller.supplier();
            });
            $('#myModal').on('hidden.bs.modal', function () {
                $('#table1').bootstrapTable('destroy');
            });

            $('#modelPurchase').on('hidden.bs.modal', function () {
                $('#table3').bootstrapTable('destroy');
            });
            $('#modelPurchase').on('show.bs.modal', function (e) {
                Controller.product();
            });

            $('#modelProduct').on('show.bs.modal', function (e) {

                var btn = $(e.relatedTarget)
                Controller.getProduct(btn);
            });

            $('#modelProduct').on('show.bs.modal', function (e) {

                var btn = $(e.relatedTarget)
                Controller.getProduct(btn);
            });

            $('#modelProduct').on('hidden.bs.modal', function () {
                $('#table2').bootstrapTable('destroy');
            });
            $("#c-purchase").on('focus', function (e) {
                var id = $("#c-supId").val();
                console.log(id)
                if (id > 0) {
                    $('#modelPurchase').modal('show');
                } else {
                    Layer.alert(__('Please select a customer'));
                }
            })
            setnums();

            //显示与关闭选择仓库模态框
            $('#modelWarehouse').on('show.bs.modal', function (e) {
                // Controller.warehouse();
            });
            $('#modelWarehouse').on('hidden.bs.modal', function () {
                $('#table4').bootstrapTable('destroy');
            });
            $('body').on('click', '.find2', function (e) {
                var id = $(this).attr("data-id");  //获取当前选择的商品ID
                Controller.warehouse(id, this);  //根据商品ID获取仓库与库存的列表
                $('#modelWarehouse').modal('show');  //显示选择仓库的模态框

            })
            Controller.api.bindevent();
        },
        edit: function () {
            //显示与关闭选择仓库模态框
            $('#modelWarehouse').on('show.bs.modal', function (e) {
                // Controller.warehouse();
            });
            $('#modelWarehouse').on('hidden.bs.modal', function () {
                $('#table4').bootstrapTable('destroy');
            });
            $('body').on('click', '.find2', function (e) {
                var id = $(this).attr("data-id");  //获取当前选择的商品ID
                Controller.warehouse(id, this);  //根据商品ID获取仓库与库存的列表
                $('#modelWarehouse').modal('show');  //显示选择仓库的模态框

            })
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }, warehouse: function (id, obj) {
            //获取当前产品id
            Table.api.init({
                extend: {
                    index_url: 'ykjp/sell/delivery/getWP?id=' + id
                }
            });

            var table = $("#table4");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                commonSearch: false,
                columns: [
                    [
                        {field: 'name', title: __('Warehouse')},
                        {field: 'p_name', title: __('Partition')},
                        {field: 'inventory', title: __('Inventory')},
                        {
                            field: 'operate',
                            width: "120px",
                            title: __('Selected'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'ajax',
                                    text: __('Selected'),
                                    title: __('Selected'),
                                    classname: 'btn btn-xs btn-success btn-magic btn-ajax',
                                    icon: 'fa fa-magic',
                                    url: 'ykjp/sell/delivery/getInventoryByid',
                                    success: function (data, ret) {

                                        var _this = $(obj).parent().parent();  //当前选择input的父级tr标签
                                        _this.find(".find2").val(data.row.w_name + '/' + data.row.p_name);  //显示当前选择的仓库库区
                                        _this.find('.inventory').val(data.row.inventory)  //赋值 可用库存
                                        _this.find('.wp_id').val(data.row.id)

                                        $('#modelWarehouse').modal('hide');
                                        //如果需要阻止成功提示，则必须使用return false;
                                        //return false;
                                    },
                                    error: function (data, ret) {
                                        Layer.alert(ret.msg);
                                        return false;
                                    }
                                },
                            ],
                            formatter: Table.api.formatter.buttons
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        }
        , supplier: function () {
            Table.api.init({
                extend: {
                    index_url: 'ykjp/sell/delivery/getSupPro?obj=1'
                }
            });

            var table = $("#table1");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                commonSearch: false,
                columns: [
                    [
                        {field: 'name', title: __('Name')},
                        {field: 'contact', title: __('Contact')},
                        {field: 'phone', title: __('Phone')},
                        {field: 'description', title: __('Description')},
                        {
                            field: 'operate',
                            width: "120px",
                            title: __('Selected'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'ajax',
                                    text: __('Selected'),
                                    title: __('Selected'),
                                    classname: 'btn btn-xs btn-success btn-magic btn-ajax',
                                    icon: 'fa fa-magic',
                                    url: 'ykjp/sell/delivery/getCustomerByid',
                                    success: function (data, ret) {
                                        $("#c-supplier").val(data.row.name);
                                        $("#c-supId").val(data.row.id);
                                        $("#c-contact").val(data.row.contact);
                                        $("#c-phone").val(data.row.phone);
                                        $("#c-address").val(data.row.address);
                                        $("#c-city").citypicker("reset");
                                        if (data.city != "") {

                                            $("#c-city").citypicker("destroy");
                                            $("#c-city").citypicker({
                                                province: data.city[0],
                                                city: data.city[1],
                                                district: data.city[2]
                                            });

                                            $("#tt").append('<select  class="second form-control"  data-url="ykjp/purchase/addorder/getWarehouse" data-query-name="pid" style="width: 100%"> <option value="2" selected="">001</option> </select>');

                                        }
                                        $('#myModal').modal('hide');
                                        //如果需要阻止成功提示，则必须使用return false;
                                        //return false;
                                    },
                                    error: function (data, ret) {
                                        Layer.alert(ret.msg);
                                        return false;
                                    }
                                },
                            ],
                            formatter: function (value, row, index) {
                                if (row.status == '禁用') {
                                    return '该客户已禁用'
                                } else {
                                    var buttons = $.extend([], this.buttons || []);
                                    return Table.api.buttonlink(this, buttons, value, row, index, 'buttons');
                                }
                            }
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        product: function () {
            Table.api.init({
                extend: {
                    index_url: 'ykjp/sell/delivery/add?obj=3'
                }
            });

            var table = $("#table3");
            var id = $("#c-supId").val();
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url + "&supid=" + id,
                pk: 'id',
                sortName: 'id',
                commonSearch: false,

                columns: [
                    [
                        {field: 'code', title: __('Code')},
                        {field: 'linkman', title: __('Contact')},
                        {field: 'phone', title: __('Phone')},
                        {field: 'remark', title: __('Description')},
                        {
                            field: 'operate',
                            width: "120px",
                            title: __('Selected'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'ajax',
                                    text: __('Selected'),
                                    title: __('Selected'),
                                    classname: 'btn btn-xs btn-success btn-magic btn-ajax',
                                    icon: 'fa fa-magic',
                                    url: 'ykjp/sell/delivery/add?obj=4',
                                    success: function (data, ret) {
                                        document.querySelector('.main-table').style.display = 'inline-table'  //显示产品
                                        //清空之前选择的旧数据
                                        var allTr = $('#table tbody tr');
                                        for (var i = 0; i < (allTr.length - 1); i++) {
                                            if (i > 0) {
                                                allTr[i].remove()  //删除条目
                                            }
                                        }
                                        $("#c-purchase").val(data.code.code);
                                        $("#c-code").val(data.code.code);
                                        $("#c-pur").val(data.code.id)
                                        var strs = "";
                                        if (data.product != "") {
                                            for (var i = 0; i < data.product.length; i++) {
                                                if (i == 0) {
                                                    var product = data.product[i];
                                                    var _this = $('#table tbody tr:eq(0)');
                                                    _this.find(".find").val(product.products.name);
                                                    _this.find(".find").attr("data-id", product.product_id);
                                                    _this.find(".find").attr("data-pro-id", product.id);
                                                    _this.find(".unit").text(product.unit);
                                                    _this.find(".find2").attr('data-id', product.product_id);
                                                    _this.find("td:eq(1)").text(product.products.sku);
                                                    _this.find("td:eq(3)").text(product.specification);
                                                    _this.find(".nums").val(product.nums);
                                                    _this.find(".unit-price").val(product.price);
                                                    _this.find(".subtotal").text(product.subtotal);
                                                    _this.find(".remarks").text(product.remarks);
                                                    if (product.products.prop != "") {
                                                        var arr = JSON.parse(product.products.prop);
                                                        var str = "";
                                                        for (var j = 0; j < arr.length; j++) {
                                                            if (typeof (arr[j]['value']) != "undefined" && arr[j]['value'] !== null) {
                                                                str += arr[j]['title'] + ":" + arr[j]['value'] + "; <br>";
                                                            }
                                                        }
                                                        _this.find("td:eq(4)").html(str);
                                                    }
                                                } else {
                                                    strs += rows(data.product[i], data.code.warehouse_partition_id);
                                                }
                                            }
                                        }
                                        if (strs != "") {
                                            $('#table tbody tr:eq(0)').after(strs);
                                        }
                                        $("#hose-fist").val(data.code.warehouse_id);
                                        $("#c-type").val(data.code.type);
                                        $("#money").val(data.code.money);
                                        $("#allMoney").text(data.code.money);
                                        $("#totalMoney").text(data.code.totalMoney);
                                        $("#totalMoneys").val(data.code.totalMoney);
                                        $("#allNums").val(data.code.totalNums);
                                        $(".totalnums").text(data.code.totalNums);
                                        $("#c-rate").val(data.code.rate);
                                        $(".second option").remove();
                                        $(".second").removeAttr("disabled");

                                        if (data.row == "") {
                                            $(".second").attr("disabled", "disabled");
                                        } else {
                                            var str = '<option value="" >请选择</option>';
                                            for (var i = 0; i < data.row.length; i++) {
                                                var op = "";
                                                if (data.code.warehouse_partition_id != "" && data.code.warehouse_partition_id == data.row[i].value) {
                                                    op = '<option value="' + data.row[i].value + '" selected="selected">' + data.row[i].name + '</option>';
                                                } else {
                                                    op = '<option value="' + data.row[i].value + '" >' + data.row[i].name + '</option>';
                                                }
                                                str += op;
                                            }
                                            $(".second").append(str);

                                        }
                                        setnums();
                                        Form.api.bindevent($("form#cxselectform"));
                                        totalNums($('#table4'))  //计算合计
                                        // console.log($("#money").val())
                                        alldisabled()  //禁止修改
                                        $('.find2').removeAttr("disabled");  //选择仓库不让他 disabled
                                        $('#modelPurchase').modal('hide');

                                        // $('#modelPurchase').modal('hide');
                                        //如果需要阻止成功提示，则必须使用return false;
                                        //return false;
                                        $(".second").val(data.code.warehouse_partition_id);
                                    },
                                    error: function (data, ret) {
                                        Layer.alert(ret.msg);
                                        return false;
                                    }
                                },
                            ],
                            formatter: Table.api.formatter.buttons
                        }
                    ]
                ]
            });

            // 为表格绑定事件

            Table.api.bindevent(table);

        }, getProduct: function (btn) {
            Table.api.init({
                extend: {
                    index_url: 'ykjp/purchase/storage/getSupPro?obj=2'
                }
            });

            var table = $("#table2");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                commonSearch: false,
                escape: false,
                columns: [
                    [
                        {field: 'name', title: __('Name')},
                        {field: 'specification', title: __('Specification')},
                        {field: 'sku', title: __('Sku')},
                        {
                            field: 'prop', title: __('Prop'), formatter: function (value, row, index) {
                                var str = "";
                                if (row.prop != "") {
                                    var arr = JSON.parse(row.prop);
                                    console.log(arr[0]);

                                    for (var i = 0; i < arr.length; i++) {

                                        if (typeof (arr[i]['value']) != "undefined" && arr[i]['value'] !== null) {
                                            str += arr[i]['title'] + ":" + arr[i]['value'] + ";<br>";
                                        }
                                    }
                                }
                                return str;
                            }
                        },
                        {
                            field: 'operate',
                            width: "120px",
                            title: __('Selected'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'ajax',
                                    text: __('Selected'),
                                    title: __('Selected'),
                                    classname: 'btn btn-xs btn-success btn-magic btn-ajax',
                                    icon: 'fa fa-magic',
                                    url: 'ykjp/purchase/addorder/getProductByid',
                                    success: function (data, ret) {
                                        var _this = btn.parent().parent();
                                        _this.find(".find").val(data.row.name);
                                        _this.find(".find").attr("data-id", data.row.id);
                                        _this.find(".unit").text(data.row.unit);
                                        _this.find("td:eq(1)").text(data.row.sku);
                                        _this.find("td:eq(3)").text(data.row.specification);
                                        if (data.row.prop != "") {
                                            var arr = JSON.parse(data.row.prop);
                                            var str = "";
                                            for (var i = 0; i < arr.length; i++) {
                                                if (typeof (arr[i]['value']) != "undefined" && arr[i]['value'] !== null) {
                                                    str += arr[i]['title'] + ":" + arr[i]['value'] + "; <br>";
                                                }
                                            }
                                            _this.find("td:eq(4)").html(str);
                                        }
                                        $('#modelProduct').modal('hide');
                                        //如果需要阻止成功提示，则必须使用return false;
                                        //return false;
                                    },
                                    error: function (data, ret) {
                                        Layer.alert(ret.msg);
                                        return false;
                                    }
                                },
                            ],
                            formatter: Table.api.formatter.buttons
                        }
                    ]
                ]
            });
            Table.api.bindevent(table);

        }
    };
    return Controller;
});

// 添加
function addRow() {
    var len = $('#table tr').length - 1;
    var lens = len - 2;
    var tempTr = '<tr>' +
            '<td>' + len + '</td>' +
            '<td></td>' +
            '<td><input data-pro-id=""  data-id="" type="text" name="" class="find" data-toggle="modal" data-target="#modelProduct" data-rule=""></td>' +
            '<td></td>' +
            '<td></td>' +
            '<td class="unit"></td>' +
            '<td class="locate"><input date-rule="required;" data-pro-id=""  type="text" name="" data-id="" class="find2"><input type="hidden" class="wp_id" name="wp_id"></td>' +
            //         ' <td> <select  class="second form-control"  name="row[warehouse_partition_id]" data-url="ykjp/purchase/addorder/getWarehouse" data-query-name="pid" style="width: 100%">'+
            // '<option value="2" selected="">001</option>'+
            //  '</select></td>'+
            '<td><input  type="number" name=""  class="inventory" value="" readonly="readonly" style="" ></td>' +
            '<td><input  type="number" name="" data-rule="required;integer;range(0~);" class="nums" onblur="totalNums(this)"></td>' +
            '<td><input  type="number" data-rule="required;" name="" onblur="calMoney(this)"  class="unit-price"></td>' +
            '<td class="subtotal"></td>' +
            '<td><textarea rows="2" class="remarks" cols="20"></textarea></td>' +
            '<td> <button type="button" class="btn btn-primary adds" onclick="addRow()">添加</button><button type="button" class="btn del  btn-default" onclick="delRow(this)" >删除</button> </td>' +
            '</tr>';
    $('#table tbody tr:eq(' + lens + ')').after(tempTr);
}

//设置序号
function setnums() {
    var len = $('#table tr').length;
    for (var i = 1; i < len - 1; i++) {
        $('#table tr:eq(' + i + ') td:first').text(i);
    }
}

function rows(obj, vs) {
    var str = "";
    if (obj.products.prop != "") {
        var arr = JSON.parse(obj.products.prop);
        for (var i = 0; i < arr.length; i++) {
            if (typeof (arr[i]['value']) != "undefined" && arr[i]['value'] !== null) {
                str += arr[i]['title'] + ":" + arr[i]['value'] + "; ";
            }
        }
    }
    var tempTr = '<tr>' +
            '<td></td>' +
            '<td>' + obj.products.sku + '</td>' +
            '<td><input data-pro-id="' + obj.id + '" data-id="' + obj.product_id + '" value="' + obj.products.name + '" type="text" name="" class="find" data-toggle="modal" data-target="#modelProduct" data-rule=""></td>' +
            '<td>' + obj.products.specification + '</td>' +
            '<td>' + str + '</td>' +
            '<td class="unit">' + obj.unit + '</td>' +
            '<td class="locate"><input date-rule="required;" data-pro-id=""  type="text" name="" data-id="' + obj.product_id + '" class="find2"><input type="hidden" class="wp_id" name="wp_id"></td>' +
            //         ' <td> <select  class="second form-control"  data-url="ykjp/purchase/addorder/getWarehouse" data-query-name="pid" style="width: 100%">'+
            // '<option value="'+vs+'" selected="selected">001</option>'+
            //  '</select></td>'+
            '<td><input  type="number" name=""  class="inventory" value="" readonly="readonly" style="" ></td>' +
            '<td><input  type="number" name="" value="' + obj.nums + '" data-rule="required;integer;range(0~);" class="nums" onblur="totalNums(this)"></td>' +
            '<td><input  type="number" value="' + obj.price + '" data-rule="required;" name="" onblur="calMoney(this)"  class="unit-price"></td>' +
            '<td class="subtotal">' + obj.subtotal + '</td>' +
            '<td><textarea rows="2" class="remarks" cols="20">' + obj.remarks + '</textarea></td>' +
            '<td> <button type="button" class="btn btn-primary adds" onclick="addRow()">添加</button><button type="button" class="btn del btn-default" onclick="delRow(this)" >删除</button> </td>' +
            '</tr>';
    return tempTr;
}

//计算总数量
function totalNums(obj) {
    var len = $('#table tr').length;
    var total = 0;
    if (obj != null) {
        calMoney(obj);
    }
    for (var i = 1; i < len - 1; i++) {
        var nums = $('#table tr:eq(' + i + ') .nums').val();
        nums = getNumValue(nums);
        if (nums == false || nums < 0) {
            total = false;
            return false;
        }
        total += nums;
    }
    if (total != false) {
        $(".totalnums").text(total);
        $("#allNums").val(total);
    }
}


function getNumValue(num) {
    if (!isNaN(num) && num != "") {
        num = parseFloat(num);
        var a = isPositiveInteger(num)
        if (a == false) {
            num = false;
        }
    } else {
        num = false;
    }
    return num;
}

function isInteger(obj) {
    return obj % 1 === 0
}

function isPositiveInteger(s) {//是否为正整数
    var re = /^[0-9]+$/;
    return re.test(s)
}
// 小计
function calMoney(obj) {
    var total = 0;
    var nums = $(obj).parent().parent().find(".nums").val();
    var nuitprice = $(obj).parent().parent().find(".unit-price").val();
    if (nuitprice == "") {
        return false;
    }
    nuitprice = parseFloat(nuitprice);
    nums = getNumValue(nums);
    if (nums == false) {
        return false;
    }
    total = nuitprice * nums;
    total = total.toFixed(2);
    $(obj).parent().parent().find(".subtotal").text(total);
    calTotalMoneys();
}
// 计算总金额
function calTotalMoneys() {
    var len = $('#table tr').length;
    var total = 0;
    for (var b = 1; b < len - 1; b++) {
        var str = '#table tr:eq(' + b + ') .subtotal';
        var a = $(str).text();
        if (a == "") {
            a = 0;
        }
        a = parseFloat(a);
        if (a == "NaN" || a == "" || a == undefined) {
            a = 0;
        }
        total += a;
    }
    $("#table #allMoney").text(total);
    var rate = $("#c-rate").val();
    rate = parseFloat(rate);
    var totalMoney = total * (1 + rate / 100);
    $("#money").val(total);
    totalMoney = totalMoney.toFixed(2);
    $("#totalMoney").text(totalMoney);
    $("#totalMoneys").val(totalMoney);

}

// 删除
function delRow(obj) {
    var pur = $("#c-pur").val();
    if (pur != "") {
        return false;
    }
    if ($('#table tbody tr').length == 2) {
        alert(__("Can't delete"));
        return false;
    }
    $(obj).parent().parent().remove();
    totalNums(null);
    calTotalMoneys()
    setnums();
}

//提交前验证
function submitData() {
    var data = $("#add-form").serialize();

    //判断是否选择了客户
    if ($("#c-supId").val() == '') {
        Toastr.error(__("Please select a customer"));
        return false;
    }

    //判断是否选择了单据
    if ($("#c-pur").val() == '') {
        Toastr.error(__("Please select a sell"));
        return false;
    }

    $('#add-form').isValid(function (v) {
        // console.log(v)
        if (v == true) {
            var len = $("#table tr").length;
            var arr = new Array();
            var arrtep = new Array();
            var c = [];
            for (var i = 1; i < len - 1; i++) {

                //判断是否选择了仓库(关联表ID)
                var wp_id = $("#table tr:eq(" + i + ")").find('.wp_id').val();
                if (wp_id == null || wp_id == '' || wp_id == 0) {
                    Toastr.error(__("Please select a warehouse"));
                    return false;
                }

                //判断库存是否足够
                var nums = $("#table tr:eq(" + i + ")").find('.nums').val();  //获取出库数量
                var inventory = $("#table tr:eq(" + i + ")").find('.inventory').val();  //获取当前可用库存

                if (parseInt(nums) > parseInt(inventory)) {
                    Toastr.error(__("Inventory shortage"));
                    return false;
                }

                var id = $("#table tr:eq(" + i + ")").find('.find').attr("data-id");
                var proid = $("#table tr:eq(" + i + ")").find('.find').attr("data-pro-id");
                if (id == "") {
                    Toastr.error(__("Please select a product"));
                    return false;
                }
                var second = $(".second").val();
                var unitPrice = $("#table tr:eq(" + i + ")").find('.unit-price').val();
                var subtotal = $("#table tr:eq(" + i + ")").find('.subtotal').text();
                var unit = $("#table tr:eq(" + i + ")").find('.unit').text();
                var remarks = $("#table tr:eq(" + i + ")").find('.remarks').val();
                var b = i - 1;
                arr.push({"product_id": id, "price": unitPrice, "nums": nums, "subtotal": subtotal, "unit": unit, "remark": remarks, "partition_id": second, "sell_pro_id": proid, 'wp_id': wp_id});
            }
            var temp = JSON.stringify(arr);
            resutlData = data + "&" + "product=" + temp;
            Fast.api.ajax({
                url: 'ykjp/sell/delivery/add?obj=5',
                data: resutlData
            }, function (data, ret) {
                //成功的回调

                if (data.result = "success") {

                    layer.msg('成功提交', {
                        time: 2000, //2s后自动关闭
                        end: function () {
                            location.href = "index";
                        }
                    });
                }
                // console.log(data);
                // return false;
            }, function (data, ret) {
                //失败的回调
                alert(ret.msg);
                return false;
            });
        }
    })

}

//编辑页面的提交
function editSubmitData() {
    var data = $("#add-form").serialize();


    $('#add-form').isValid(function (v) {
        // console.log(v)
        if (v == true) {
            var len = $("#table tr").length;
            var arr = new Array();
            var arrtep = new Array();
            var c = [];
            for (var i = 1; i < len - 1; i++) {

                //判断是否选择了仓库(关联表ID)
                var wp_id = $("#table tr:eq(" + i + ")").find('.wp_id').val();
                if (wp_id == null || wp_id == '' || wp_id == 0) {
                    Toastr.error(__("Please select a warehouse"));
                    return false;
                }

                //判断库存是否足够
                var nums = $("#table tr:eq(" + i + ")").find('.nums').val();  //获取出库数量
                var inventory = $("#table tr:eq(" + i + ")").find('.inventory').val();  //获取当前可用库存

                if (parseInt(nums) > parseInt(inventory)) {
                    Toastr.error(__("Inventory shortage"));
                    return false;
                }

                var second = $(".second").val();
                var unitPrice = $("#table tr:eq(" + i + ")").find('.unit-price').val();
                var subtotal = $("#table tr:eq(" + i + ")").find('.subtotal').text();
                var unit = $("#table tr:eq(" + i + ")").find('.unit').text();
                var remarks = $("#table tr:eq(" + i + ")").find('.remarks').val();
                var pro_id = $("#table tr:eq(" + i + ")").find('.find2').attr('data-id')
                var b = i - 1;
                arr.push({'pro_id': pro_id, "remark": remarks, 'wp_id': wp_id});
            }
            var temp = JSON.stringify(arr);
            resutlData = data + "&" + "product=" + temp;
            Fast.api.ajax({
                url: 'ykjp/sell/delivery/edit',
                data: resutlData
            }, function (data, ret) {
                //成功的回调

                if (data.result = "success") {

                    layer.msg('成功提交', {
                        time: 2000, //2s后自动关闭
                        end: function () {
                            location.href = "index";
                        }
                    });
                }
                // console.log(data);
                // return false;
            }, function (data, ret) {
                //失败的回调
                alert(ret.msg);
                return false;
            });
        }
    })

}

// 禁用标签
function alldisabled() {
    $(".del").attr("disabled", "disabled");
    $(".adds").attr("disabled", "disabled");
    $('#table tbody tr input').attr("disabled", "disabled");
}


function submitUpdate(obj) {
    var data = $("#add-form").serialize();
    // console.log(data)
    if ($("#c-supId").val() == '') {
        Toastr.error(__("Please select a merchant"));
        return false;
    }
    if ($("#hose-fist").val() == 0) {
        Toastr.error(__("Please select a warehouse"));
        return false;
    }
    $('#add-form').isValid(function (v) {
        // console.log(v)
        if (v == true) {
            var len = $("#table tr").length;
            var arr = new Array();
            var arrtep = new Array();
            var c = [];
            for (var i = 1; i < len - 1; i++) {
                var id = $("#table tr:eq(" + i + ")").find('.find').attr("data-id");
                var proid = $("#table tr:eq(" + i + ")").find('.find').attr("data-pro-id");
                if (id == "") {
                    Toastr.error(__("Please select a product"));
                    return false;
                }
                var second = $(".second").val();
                var nums = $("#table tr:eq(" + i + ")").find('.nums').val();
                var wait_nums = $("#table tr:eq(" + i + ")").find('.wait_nums').val();
                var unitPrice = $("#table tr:eq(" + i + ")").find('.unit-price').val();
                var subtotal = $("#table tr:eq(" + i + ")").find('.subtotal').text();
                var unit = $("#table tr:eq(" + i + ")").find('.unit').text();
                var remarks = $("#table tr:eq(" + i + ")").find('.remarks').val();
                var data_id = $("#table tr:eq(" + i + ")").find('.prid').attr("data-id");
                var data_pro = $("#table tr:eq(" + i + ")").find('.prid').attr("data-pro-id");
                var wp_id = $('#table tr:eq(' + i + ')').find('.wp_id').val()
                var b = i - 1;
                console.log(data_pro);
                if (data_pro != "" && data_pro > 0) {
                    if (wait_nums < nums) {
                        Toastr.error(__("Inventory shortage"));
                        return false;
                    }
                }
                arr.push({"product_id": id, "price": unitPrice, "nums": nums, "subtotal": subtotal, "unit": unit, "remark": remarks, "partition_id": second, "sell_pro_id": proid, "data_id": data_id, "purchase_proid": data_pro, 'wp_id': wp_id});
            }
            var temp = JSON.stringify(arr);
            resutlData = data + "&" + "product=" + temp;
            Fast.api.ajax({
                url: 'ykjp/purchase/storage/updateData?ids=' + obj,
                data: resutlData
            }, function (data, ret) {
                //成功的回调

                if (data.result = "success") {

                    layer.msg('成功提交', {
                        time: 2000, //2s后自动关闭
                        end: function () {
                            location.reload();
                        }
                    });
                }
                // console.log(data);
                // return false;
            }, function (data, ret) {
                //失败的回调
                // alert(ret.msg);
                return false;
            });
        }
    })

}


function approval(obj, id) {
    Fast.api.ajax({
        url: "ykjp/purchase/sto_audit/approval?ids=" + id,
        data: {"type": obj}
    }, function (data, ret) {
        //成功的回调
        if (data.result = "success") {
            layer.msg('成功提交', {
                time: 2000, //2s后自动关闭
                end: function () {
                    location.reload();
                }
            });
        }
    }, function (data, ret) {
        alert(ret.msg);
        return false;
    });
}

function storage(id) {
    Fast.api.ajax({
        url: "ykjp/purchase/storage/inventory?ids=" + id,
    }, function (data, ret) {
        //成功的回调
        if (data.result = "success") {
            layer.msg('入库成功', {
                time: 2000, //2s后自动关闭
                end: function () {
                    location.reload();
                }
            });
        }
    }, function (data, ret) {
        alert(ret.msg);
        return false;
    });
}


//作废出库单
function abandon(ids) {
    var str = "<div  style='width:80%;margin-left:auto;margin-right:auto'><textarea class='reason' rows='3' cols='38'></textarea></div>";
    layer.open({
        id: 1,
        type: 1,
        title: '请输入作废理由',
        skin: 'layui-layer-rim',
        area: ['450px', '300px'],

        content: str
        ,
        btn: ['保存', '取消'],
        btn1: function (index, layero) {
            var reason = $(".reason").val().trim();
            if (reason == null || reason == '' || reason == undefined) {
                layer.alert('请输入作废理由')
                return false;
            } else {

                //执行作废销售单操作
                Fast.api.ajax({
                    url: 'ykjp/sell/delivery/abandon',
                    data: {
                        'ids': ids,
                        'reason': reason
                    }
                }, function (data, ret) {
                    //成功的回调
                    if (data.result = "success") {

                        layer.msg('成功提交', {
                            time: 2000, //2s后自动关闭
                            end: function () {
                                location.reload();
                            }
                        });
                    }
                    // console.log(data);
                    // return false;
                }, function (data, ret) {
                    //失败的回调
                    layer.alert(data.result);
                    return false;
                });


            }

        },
        btn2: function (index, layero) {
            layer.close(index);
        }

    });
}

//反审核
function Anti(id) {
    Fast.api.ajax({
        url: "ykjp/sell/delivery/Anti?ids=" + id,
    }, function (data, ret) {
        //成功的回调

        if (data.result = "success") {
            location.reload();
        }
    }, function (data, ret) {
        Layer.alert(ret.msg);
        return false;
    });
}

// //添加打印
// jQuery('body').delegate('#prind', 'click', function () {
//     var selector = Boolean(jQuery('body').find(".prindBody")) ? jQuery('body').find(".prindBody") : jQuery('body').find(".prindBody");
//     jQuery(selector).print({
//         addGlobalStyles: true,
//         stylesheet: '/assets/css/print.css',
//         rejectWindow: true,
//         noPrintSelector: ".no-print",
//         iframe: true,
//         append: null,
//         prepend: '<div style="text-align: center;font-size: 25px;padding-bottom:20px">销售出库单 </div>'
//     });
//     return false;
// });

function printPdf() {
    var headerTitle = $(".panel-heading").text();
    $(".panel-heading").text("销售出库单").css({
        "width":"300px",
        "margin-left":"auto",
        "margin-right":"auto",
        "font-size":"50px",
    });

    $(".prindBody .print-row,.prindBody .code label,.prindBody .print-row,.prindBody .code div").removeClass("col-xs-12").css({"float":"left"});
    $(".prindBody .print-row").removeClass("col-xs-12").addClass("col-xs-6").css({"float":"left"});
    $(".prindBody .print-row div , .prindBody .print-row label,.prindBody .print-remark div,.prindBody .print-remark label").removeClass("col-xs-12").css({"float":"left"});

    $(".no-print").css('display','none');
    $("#ribbon").css('display','none');
    $("#print").css('display','none');
    window.print();
    $(".panel-heading").text(headerTitle).removeAttr("style");

    $(".prindBody .print-row,.prindBody .code label,.prindBody .print-row,.prindBody .code div").addClass("col-xs-12").removeAttr("style");
    $(".prindBody .print-row").removeClass("col-xs-6").addClass("col-xs-12").removeAttr("style");
    $(".prindBody .print-row div , .prindBody .print-row label,.prindBody .print-remark div,.prindBody .print-remark label").addClass("col-xs-12").removeAttr("style");

    $(".no-print").css('display','block');
    $("#print").css('display','block');
    $("#ribbon").css('display','block');
}